import React, { useState, useEffect } from 'react';
import { Form, Card, Row, Button, message, Spin, Divider } from 'antd';

import { history } from 'umi'
import request from '@/utils/request';
import { eventTrack } from '@/utils/track';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { addJob } from '@/services/organization';

import helper from '@/utils/auth/helper';
import { hideSalaryTable } from '@/utils/utils';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { PostBasicInfo, PostSalaryRef } from './components/PostForm';
import { useJobDetail } from './hooks';
import styles from './index.less';

const doubleStyle = {
    labelCol: {
        xs: 6
    },
    wrapperCol: {
        xs: 16
    }
};
const singleStyle = {
    labelCol: {
        xs: 3
    },
    wrapperCol: {
        xs: 20
    }
};
const Edit = ({ form, location: { query } }) => {
    const [detailLoading, detail, setDetailLoading] = useJobDetail(query);
    const { validateFields } = form;
    const isEdit = query.action === 'edit';
    const isDetail = query.action === 'detail';
    const cardTitle = (() => {
        let title = '';
        if (isDetail) {
            title = '职位详情';
        } else if (isEdit) {
            title = '编辑职位';
        } else {
            title = '添加职位';
        }
        return title;
    })();

    const [isAllLoaded, setIsAllLoaded] = useState({ grade: false });
    const [isDisabled, setIsDisabled] = useState(true);
    useEffect(() => {
        if (isEdit) {
            if (detail && Object.keys(detail).length > 0) {
                if (isAllLoaded.grade === true) {
                    setIsDisabled(false);
                }
            }
        } else {
            setIsDisabled(false);
        }
    }, [detail, isAllLoaded]);

    const duplicateMessage = resultData => (
        <>
            <div className={styles.errMsg}>
                该职位类别和职级下已有职位
                <Button
                    type="link"
                    onClick={() => {
                        message.destroy();
                        history.push({
                            pathname: '/office/personnelManagement/organization/job/edit',
                            query: { id: resultData.id, action: 'detail' }
                        });
                    }}
                >
                    {resultData.postName}
                </Button>
                ，点击可前往该职位详情界面
            </div>
        </>
    );

    // 数据报错后跳转到 发起职位审批的页面
    const handleSubmit = () => {
        validateFields(async (err, values) => {
            if (!err) {
                // 流程不存在提示
                const { workFlowUrl } = await hasWorkFlowByType('PostApply');
                if (!workFlowUrl) {
                    return;
                }
                const { positionCodes, ...params } = values;
                const requestParam = {
                    ...params
                };
                requestParam.operationType = isEdit ? 1 : 0;
                if (isEdit) {
                    requestParam.positionCode = detail.positionCode;
                }
                setDetailLoading(true);
                const { code, msg, data } = await addJob(requestParam);

                if (code === 60018) {
                    const { positionCode } = requestParam;
                    // const response = await request(`/api/oa/v1/post/getPostByPostCode/${postCode}`, {
                    const response = await request(`/api/oa/v2/position/detail/get/${positionCode}`, {
                        method: 'get'
                    });
                    if (response.code === 10000) {
                        message.error(duplicateMessage(response.data));
                    }
                } else if (code === 10000) {
                    // message.success(isEdit ? '修改成功' : '新增成功');
                    // actProcessDefinitionId: "03a9e4b7-c188-11ea-b93e-765e309f4988"
                    // actProcessDeploymentId: "03a48d85-c188-11ea-b93e-765e309f4988"
                    // 埋点
                    await eventTrack({
                        eventName: isEdit ? 'organization_job_edit_sumbit_click' : 'organization_job_add_sumbit_click',
                        eventProps: { status: 0 }
                    });
                    history.push(`${workFlowUrl}${data}&bId=${data}`); // bid这个参数已经没用了，不过为了兼容岗位流程没删除！！
                } else {
                    message.error(msg);
                    // 埋点
                    eventTrack({
                        eventName: isEdit ? 'organization_job_edit_sumbit_click' : 'organization_job_add_sumbit_click',
                        eventProps: { status: 1, error_info: msg }
                    });
                }
                setDetailLoading(false);
            }
            console.log(err);
        });
    };

    const subProps = {
        isEdit,
        isDetail,
        query,
        form,
        detail,
        doubleStyle,
        singleStyle
    };

    useEffect(() => {
        if (query.action === 'detail') {
            form.resetFields();
        }
    }, [query.action]);

    return (
        <PageHeaderWrapper>
            <Card
                title={cardTitle}
                extra={
                    isDetail ? (
                        helper.checkCode('office:org:posts:edit') && (
                            <Button
                                type="primary"
                                onClick={() => {
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/job/edit',
                                        query: {
                                            ...query,
                                            action: 'edit'
                                        }
                                    });
                                }}
                            >
                                编辑
                            </Button>
                        )
                    ) : (
                        <Row>
                            {/* 埋点 */}
                            <Button
                                onClick={() => {
                                    message.destroy();
                                    eventTrack({
                                        eventName: isEdit
                                            ? 'organization_job_edit_cancel_click'
                                            : 'organization_job_add_cancel_click'
                                    });
                                    history.push('/office/personnelManagement/organization/job');
                                }}
                            >
                                取消
                            </Button>
                            <Button
                                style={{ marginLeft: 16 }}
                                type="primary"
                                onClick={() => handleSubmit()}
                                disabled={isDisabled}
                            >
                                下一步
                            </Button>
                        </Row>
                    )
                }
            >
                <div style={{ position: 'relative' }}>
                    <Spin spinning={detailLoading}>
                        <Form layout="horizontal" className={styles.postEdit}>
                            <PostBasicInfo {...subProps} isAllLoaded={isAllLoaded} setIsAllLoaded={setIsAllLoaded} />
                            {/* TODO 现无角色概念，先去除，后续改造 */}
                            {/* <Divider /> */}
                            {/* <PostAuth {...subProps} /> */}
                            {!hideSalaryTable && (
                                <>
                                    <Divider />
                                    <PostSalaryRef {...subProps} />
                                </>
                            )}
                        </Form>
                    </Spin>
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(Form.create()(React.memo(Edit)));
